<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-24
 * Time: 11:36
 */

namespace app\api\model\oc\v1;

use app\api\service\OCOAWebAppData;
use app\common\model\WeChatUser;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use think\facade\App;
use think\facade\Request;

class WeChatUserAdminAuth
{
    /**
     * 微信管理员用户登录授权请求处理
     * @return int
     */
    public static function handleAdminAuthLoginRequest()
    {
        $code = Request::get('code', '');

        if (empty($code)) {
            throw new \Exception('[微信公众号]code码为空，请求失败');
        }

        $OCOAWebApp = new OCOAWebAppData();

        // 获取access_token
        $access_token = $OCOAWebApp->getWebAppAccessToken($code);
        if (!isset($access_token['access_token']) || empty($access_token['access_token'])) {
            return -1;
        }
        // 拉取用户信息
        $user_data = $OCOAWebApp->getUserInfo($access_token['access_token'],$access_token['openid']);
        if (!isset($user_data['openid']) || empty($user_data['openid'])) {
            return -2;
        }

        // 判断数据库中是否已有用户数据
        $user = WeChatUser::where([['oc_openid','=',$user_data['openid']]])
            ->find();

        if ($user) {
            WeChatUser::updateUserInfoByOCOAWebApp($user_data);
        } else {
            WeChatUser::addUserByOCOAWebApp($user_data);
        }

        return 0;
    }

    /**
     * 生成微信用户授权用户信息二维码
     * @return mixed
     */
    public static function generateAdminAuthQRCode()
    {
        $root_path = App::getRootPath();
        $save_path = $root_path . 'public/storage/admin_auth_qrcode';
        $file_name = $save_path . '/admin_auth_login.png';
        if (!is_dir($save_path)) {
            // 文件夹不存在，需要创建
            @mkdir($save_path);
        }

        if (!is_file($file_name)) {

//            $redirect_url = get_system_config('site_url') . '/api.php/oc/v1/login/admin_auth?redirect_login=1';
//            $url = (new OCOAWebAppData())->generateLoginUrl($redirect_url);

            $url = get_system_config('site_url') . '/api.php/oc/v1/login/admin_auth?redirect_login=1';
                // 如果文件不存在，则创建
            // 二维码配置
            $options = new QROptions([
                'version' => QRCode::VERSION_AUTO,
                'outputType' => QRCode::OUTPUT_IMAGE_PNG,
                'eccLevel' => QRCode::ECC_H,
                'scale' => 8,
                'imageBase64' => false,
            ]);

            $qrcode = new QRCode($options);
            $file = $qrcode->render($url);

            // 保存到文件
            file_put_contents($file_name, $file);
        }

        return str_replace($root_path . 'public', get_system_config('site_url'), $file_name);
    }
}